import { ref, onBeforeMount } from 'vue'
import { doGetWxAppId } from '@/apis/good/index'
import { useGetQrcode } from './useGetQrcode'
// @ts-ignore
import Mshare from 'm-share' //引入微信分享插件
const { handleGetQrcode } = useGetQrcode()

/**
 * 分享
 * @returns {
 * Mshare: 分享方法
 * innitConfig: 分享配置
 *  }
 */
export const useShare = () => {
  // @ts-ignore
  const baseUrl = import.meta.env.VITE_BASE_H5_VIEW_URL
  let imgUrl = ''
  let link = ''
  onBeforeMount(async () => {
    isWechantFun()
    await handleGetQrcode((qrcode) => {}, getWxConfig)
    Mshare.init(innitConfig()) //插件初始化
    if (isWechant.value) {
      getWxConfig()
    }
  })
  // 当前环境
  const isWechant = ref(false)
  // 判断当前环境
  const isWechantFun = () => {
    // 判断是否在微信环境
    let ua = window.navigator.userAgent.toLowerCase()
    const matchArr = ua.match(/MicroMessenger/i)
    if (matchArr) {
      isWechant.value = matchArr[0] === 'micromessenger'
    }
  }
  // 获取 微信配置
  const getWxConfig = async () => {
    let data_ = {
      appId: '',
      nonceStr: '',
      signature: '',
      timestamp: '',
      url: '',
    }
    try {
      const { data, code } = await doGetWxAppId(baseUrl)
      if (code !== 200)
        return uni.showToast({
          icon: 'none',
          title: '微信配置失败',
        })
      data_ = data
    } catch (error) {
      return uni.showToast({
        icon: 'none',
        title: '微信配置失败',
      })
    }

    const { appId, nonceStr, signature, timestamp, url } = data_
    link = url
    Mshare.wxConfig({
      title: '微信分享的标题',
      desc: '微信分享的介绍详情',
      imgUrl,
      link,
      wx: {
        appId,
        timestamp,
        nonceStr,
        signature,
      },
      infoMap: {
        wx: {
          title: '微信分享的标题',
          desc: '微信分享的介绍详情',
          imgUrl,
          link,
        },
      },
    })
  }

  // 初始化配置
  const innitConfig = () => {
    // Mshare初始化
    let config = {
      title: '微信分享的标题',
      desc: '微信分享的介绍详情',
      imgUrl,
      link,
      types: ['wx', 'wxline', 'qq', 'qzone', 'sina'],
      infoMap: {
        wx: {
          title: '微信分享的标题',
          desc: '微信分享的介绍详情',
          imgUrl,
          link,
        },
      },
      fnDoShare(type: any) {
        console.log('分享回调:', type)
      },
    }
    return config
  }
  return {
    Mshare,
    innitConfig,
  }
}
